package head

import (
	"context"
	"grpc/internal/global"
	"grpc/internal/pkg"
	"grpc/internal/types"
	"grpc/pb"
	"log"
)

type UserService struct {
	pb.UnimplementedPbServer
}

func (s *UserService) UserRegister(ctx context.Context, in *pb.UserRegisterReq) (pb.UserRegisterResp, error) {

	if len(in.Phone) != 11 {
		log.Fatal("手机号格式错误")
	}

	set := global.RedisClient.Set("UserPhone", in.Phone, 0)

	if set.Err() != nil {
		log.Fatal("发送验证码失败")
	}

	if in.Username == "" && len(in.Username) >= 8 && 6 <= len(in.Username) {
		log.Fatal("用户名不能为空，用户名格式，注册失败")
	}

	if in.Password == "" && len(in.Password) > 20 && len(in.Password) < 6 {
		log.Fatal("用户密码不能为空，注册失败")
	}

	users := types.Users{
		Username: in.Username,
		Password: in.Password,
		UserUrl:  in.UserUrl,
		Phone:    in.Phone,
	}

	global.Db.Table("users").Create(&users)

	pkg.GetJwtToken("")
	pkg.ParseJwtToken("")

	return pb.UserRegisterResp{Id: int64(users.ID)}, nil
}

func (s *UserService) UserLogin(ctx context.Context, in *pb.UserLoginReq) (pb.UserLoginResp, error) {

	var users types.Users

	result := global.Db.Table("users").Where("phone = ?", in.Phone).First(&users)

	Variable := result.RowsAffected // 返回找到的记录数
	if Variable == 0 {
		log.Fatal("此用户为空")
	}
	err := result.Error
	if err != nil {
		log.Fatal("查询失败")
	}

	if users.Password != in.Password {
		log.Fatal("密码输入错误，登录失败")
	}

	return pb.UserLoginResp{
		Id:       int64(users.ID),
		Username: users.Username,
		Password: users.Password,
		UserUrl:  users.UserUrl,
		Phone:    users.Phone,
		Email:    users.Email,
		Age:      int64(users.Age),
		Address:  users.Address,
	}, nil
}

/*

// 实现方法
func (s *UserInfoService) GetUserInfo(ctx context.Context, req *pb.UserRequest) (resp *pb.UserResponse, err error) {
   // 通过用户名查询用户信息
   name := req.Name
   // 数据里查用户信息
   if name == "zs" {
      resp = &pb.UserResponse{
         Id:    1,
         Name:  name,
         Age:   22,
         Hobby: []string{"Sing", "Run"},
      }
   }
   return
}
*/
